import React, {Component} from 'react';
import {connect, ConnectedProps} from 'react-redux';
import {StyleSheet, View} from 'react-native';
import SnapCarousel, {
  ParallaxImage,
  Pagination,
  AdditionalParallaxProps,
} from 'react-native-snap-carousel';
import {RootState} from '@/models/index';
import {hp, viewportWidth, wp} from '@/utils/index';
import styles from '@/assets/styles/index.style';

const itemWidth = wp(90) + wp(2) * 2;

const _styles = StyleSheet.create({
  imageContainer: {
    width: itemWidth,
    height: hp(26),
    borderRadius: 8,
  },
  image: {
    ...StyleSheet.absoluteFillObject,
    resizeMode: 'cover',
  },
});

class Carousel extends Component<IProps> {
  state = {
    activeSlide: 0,
  };

  _renderItemWithParallax(
    {item}: {item: string},
    parallaxProps?: AdditionalParallaxProps,
  ) {
    return (
      <ParallaxImage
        source={{uri: item}}
        style={_styles.image}
        containerStyle={_styles.imageContainer}
        parallaxFactor={0.35}
        showSpinner={true}
        spinnerColor="rgba(0, 0, 0, 0.25)"
        {...parallaxProps}
      />
    );
  }

  onSnapToItem = (index: number) => {
    this.setState({
      activeSlide: index,
    });
  };

  render() {
    const {
      home: {carouselList},
    } = this.props;

    return (
      <>
        <SnapCarousel
          data={carouselList}
          renderItem={this._renderItemWithParallax}
          sliderWidth={viewportWidth}
          itemWidth={itemWidth}
          hasParallaxImages
          loop={true}
          loopClonesPerSide={2}
          autoplayDelay={500}
          autoplayInterval={3000}
          inactiveSlideScale={0.94}
          inactiveSlideOpacity={0.7}
          onSnapToItem={this.onSnapToItem}
        />
        <View style={styles.paginationWrapper}>
          <Pagination
            dotsLength={carouselList.length}
            activeDotIndex={this.state.activeSlide}
            containerStyle={styles.paginationContainer}
            dotStyle={styles.paginationDot}
            dotColor={'rgba(255, 255, 255, 0.92)'}
            inactiveDotColor={'#1a1917'}
            inactiveDotOpacity={0.4}
            inactiveDotScale={0.6}
          />
        </View>
      </>
    );
  }
}

const mapStateToProps = (state: RootState) => state;

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {}

export default connector(Carousel);
